<template>
  <div class="app-container">
    <el-card class="mar_bottom">
      <el-search-form label-width="90px" @search="onSearch" @reset="onReset">
        <el-form-item>
          <el-select
            size="small"
            style="width: 100px; margin-right: -2px"
            v-model="timeType"
            placeholder="请选择"
          >
            <el-option label="创建时间" value="createDate"></el-option>
            <el-option label="订单时间" value="orderTime"></el-option>
          </el-select>
          <el-date-picker
            size="small"
            v-model="searchBody.timeRange"
            style="width: 350px"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="城市">
          <el-cascader
            v-model="regionIdList"
            size="small"
            :options="regionTree"
            :props="{
              label: 'name',
              value: 'id',
              checkStrictly: true,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="订单ID">
          <el-input
            clearable
            size="small"
            v-model="searchBody.id"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="业主手机号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.phone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="注册人账号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.userPhone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="注册人上级号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.pUserPhone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核日期">
          <el-date-picker
            v-model="searchBody.audiDate"
            type="date"
            placeholder="选择日期"
            @change="handleChangeAudiDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-search-form>
      <el-button type="primary" size="small" @click="handleClick('exportOut')"
      >导出数据</el-button
      >
    </el-card>

    <el-card>
      <div>
        <el-button
          type="primary"
          size="small"
          @click="handleClick('createNewOrder')"
        >创建新订单</el-button
        >
      </div>
      <el-tabs
        style="margin-top: 15px"
        v-model="searchBody.zhuangtai"
        @tab-click="getData"
      >
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="出单" name="1"></el-tab-pane>
        <el-tab-pane label="已量房" name="3"></el-tab-pane>
        <el-tab-pane label="已签单" name="5"></el-tab-pane>
        <el-tab-pane label="跑单" name="2"></el-tab-pane>
        <el-tab-pane label="无效" name="4"></el-tab-pane>
      </el-tabs>

      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
      <div class="have-pagination-container">
        <el-table v-loading="loading.list" :data="list" border >
          <el-table-column
            label="线索ID"
            prop="id"
            align="center"
            width="160"
          ></el-table-column>

          <el-table-column
            label="业主"
            prop="name"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="手机"
            prop="phone"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="城市"
            prop="cityValue"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="小区"
            prop="xiaoqu"
            align="center"
            width="160"
          ></el-table-column>

          <el-table-column
            label="面积"
            prop="mianji"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="预算"
            prop="yusuanValue"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="创建时间"
            prop="createDate"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="量房照片"
            prop="liangfangImage"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 30px; height: 30px"
                :src="scope.row.liangfangImage"
                :preview-src-list="[scope.row.liangfangImage]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
<!--          <el-table-column
            label="状态"
            prop="zhuangtaiValue"
            align="center"
            width="160"
          ></el-table-column>-->
<!--          <el-table-column
            label="订单价格"
            prop="orderPrice"
            align="center"
            width="160"
          ></el-table-column>-->
<!--          <el-table-column
            label="审核时间"
            prop="audiDate"
            align="center"
            width="160"
          ></el-table-column>-->
<!--         -->

          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleClick('xiangqing', scope.row)"
              >详情</el-button
              >
              <el-button
                              type="primary"
                              size="small"
                              :disabled="scope.row.isShangwu !== '1'"
                              @click="handleClick('shanchu', scope.row)"
                            >删除</el-button
                            >
<!--              <el-button
                type="primary"
                size="small"
                @click="handleClick('shenhe', scope.row)"
                :disabled="scope.row.audiStatus === '5'"
              >审核</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="handleClick('liangfang', scope.row)"
                :disabled="scope.row.isLiangfang === '1'"
              >已量房</el-button
              >-->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </el-card>

    <!-- 查看详情信息 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle2"
      width="75%"
      :visible.sync="editDialog"
    >
      <div>
        <XiangDiaShangwu :alldata="xiangDataShangwu"></XiangDiaShangwu>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="queren"> 确认修改 </el-button>
        <el-button @click="editDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情信息 -->
    <XiangDiaShangwu ref="xiaDiaShangwuRef" @closeDiaFun="closeXiaDia"></XiangDiaShangwu>

    <!-- 接单/派单/订单/结算... -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="lookDialog"
      fullscreen
    >
      <div class="power_right">
        <el-button
          title="刷新"
          icon="el-icon-refresh-right"
          size="medium"
          circle
          @click="getData2"
        ></el-button>
        <el-dropdown :hide-on-click="false" trigger="click">
          <el-button
            style="margin-left: 10px"
            title="筛选列"
            icon="el-icon-menu"
            size="medium"
            circle
          ></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item, idx) in tableColumn2" :key="idx">
              <el-checkbox v-model="item.checked">{{ item.label }}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" @command="handleCommand">
          <el-button
            style="margin-left: 10px"
            title="导出"
            icon="el-icon-upload2"
            size="medium"
            circle
          ></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="csv">导出csv格式文件</el-dropdown-item>
            <el-dropdown-item command="xls">导出xls格式文件</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-table show-summary v-loading="loading.list2" :data="list">
        <el-table-column
          v-if="tableColumn2[0].checked"
          label="线索ID"
          prop="id"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[1].checked"
          label="订单GUID"
          prop="id"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[2].checked"
          label="线索UUID"
          prop="id"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[3].checked"
          label="线索姓名"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[4].checked"
          label="线索城市"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[5].checked"
          label="线索时间"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[6].checked"
          label="渠道主"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[7].checked"
          label="达人"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[8].checked"
          label="派单时间"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[9].checked"
          label="接单时间"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[10].checked"
          label="产生需求"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[11].checked"
          label="需求时间(订单)"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[12].checked"
          label="需求城市"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[13].checked"
          label="渠道主奖励"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[14].checked"
          label="达人奖励"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[15].checked"
          label="结算状态"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          v-if="tableColumn2[16].checked"
          label="结算时间"
          prop="name"
          align="center"
        ></el-table-column>
      </el-table>
    </el-dialog>
    <!-- 派单弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle3"
      :visible.sync="paidanDialog"
      fullscreen
    >
      <el-form label-suffix=":">
        <el-form-item label="业主">{{ paidanData.yezhu }}</el-form-item>
        <el-form-item label="地址">{{ paidanData.address }}</el-form-item>
        <el-form-item label="已派单">
          <el-table :data="paidanData.yipaidan">
            <el-table-column
              label="商家"
              prop="jiazhuangPlatformName"
              align="center"
            ></el-table-column>
            <el-table-column
              label="派单时间"
              prop="paidanDate"
              align="center"
            ></el-table-column>
            <el-table-column
              label="操作员"
              prop="createUser"
              align="center"
            ></el-table-column>
            <el-table-column
              label="接单时间"
              prop="jiedanDate"
              align="center"
            ></el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="未派单">
          <el-table
            border
            :data="paidanData.weipaidan"
            @selection-change="onSelectionChange"
          >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column
              label="商家"
              prop="jiazhuangPlatformName"
              align="center"
            ></el-table-column>
            <el-table-column
              label="最后派单时间"
              prop="lastPaidanDate"
              align="center"
            ></el-table-column>
            <el-table-column
              label="最后接单时间"
              prop="lastJiedanDate"
              align="center"
            ></el-table-column>
            <el-table-column
              label="操作员"
              prop="createUser"
              align="center"
            ></el-table-column>
            <el-table-column
              label="标题"
              prop="title"
              align="center"
            ></el-table-column>
            <el-table-column
              label="日记"
              prop="logs"
              align="center"
            ></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="paidanDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSure('paidan')"
        >派 单</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  paidanOrder,
  selectPaidanPageVo,
  selectRegionTree,
  sysDictbyMultiType,
  addNewOrder,
  editXiansuo,
  exportInData,
  exportOutData,
  exportSysRegion,
  selectJiaZhuangOrderPage,
  jiazhuangdingdanshenhe,
  selectTotalOrderPrice,
  exportJiazhuangOrderList,
  houtaiSetLiangfang,
  selecJiaOrderPageDataForShangwu, selectJiaOrderDetailVoForShangwu,
  shangwuShanchuOrder,
} from "@/api/api.js";
import { sysDict_delete } from "@/api/dataDict";
import { downloadFile } from "@/utils/index";
import XiangDiaShangwu from "./xiangDiaShangwu.vue";

const getDefaultForm = () => ({
  name: null,
  sex: null,
  phone: null,
  addrCode: null,
  address: null,
  mianji: null,
  resouces: null,
  remark: null,
  logs: null,
  marketingType: null,
});
const getDefaultSearchBody = () => ({
  timeRange: null,
  resource: null,
  phone: null,
  yezhu: null,
  orderNo: null,
  userIdList: null,
  id: null,
  zhuangtai: "0",
  audiDate: null,
  isLiangfang: null,
  pUserPhone: null,
  userPhone: null,
  xiansuoStatus:null,
});
export default {
  components: {
    XiangDiaShangwu,
  },
  data() {
    return {
      regionTree:[],
      shenheLoading: false,
      regionIdList:null,
      timeType: "createDate",
      searchType: "phone",
      dialogTitle: "",
      dialogTitle2: "",
      dialogTitle3: "",
      handleType: "",
      pageNo: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizeOpts: [20, 50, 100, 300, 500],
      loading: {
        list: false,
        list2: false,
      },
      list: [],
      paidanData: {},
      selectRow: [], // 选中行
      lookDialog: false,
      editDialog: false, // 查看详情弹窗
      paidanDialog: false,
      updateForm: getDefaultForm(),
      searchBody: getDefaultSearchBody(),
      totalOrderPrice: 0,
      tableColumn: [
        {
          label: "线索ID",
          checked: true,
        },
        {
          label: "线索业主",
          checked: true,
        },
        {
          label: "线索手机",
          checked: true,
        },
        {
          label: "线索城市",
          checked: true,
        },
        {
          label: "派单",
          checked: true,
        },
        {
          label: "接单",
          checked: true,
        },
        {
          label: "订单",
          checked: true,
        },
        {
          label: "结算",
          checked: true,
        },
        {
          label: "标记",
          checked: true,
        },
        {
          label: "更新小计",
          checked: true,
        },
        {
          label: "来源",
          checked: true,
        },
        /* {
          label: "管理员/渠道主/达人",
          checked: true,
        },*/
        /*{
          label: "手机归属",
          checked: true,
        },
        {
          label: "线索时间",
          checked: true,
        },
        {
          label: "需求时间（订单）",
          checked: true,
        },
        {
          label: "更新时间",
          checked: true,
        },
        {
          label: "更新人",
          checked: true,
        },*/
      ],
      tableColumn2: [
        {
          label: "线索ID",
          checked: true,
        },
        {
          label: "订单GUID",
          checked: false,
        },
        {
          label: "线索UUID",
          checked: true,
        },
        {
          label: "线索姓名",
          checked: true,
        },
        {
          label: "线索城市",
          checked: true,
        },
        {
          label: "线索时间",
          checked: true,
        },
        {
          label: "渠道主",
          checked: true,
        },
        {
          label: "达人",
          checked: true,
        },
        {
          label: "派单时间",
          checked: true,
        },
        {
          label: "接单时间",
          checked: true,
        },
        {
          label: "产生需求",
          checked: true,
        },
        {
          label: "需求时间(订单)",
          checked: true,
        },
        {
          label: "需求城市",
          checked: true,
        },
        {
          label: "渠道主奖励",
          checked: true,
        },
        {
          label: "达人奖励",
          checked: true,
        },
        {
          label: "结算状态",
          checked: true,
        },
        {
          label: "结算时间",
          checked: true,
        },
      ],

      xiangData: {
        name:null,
      },
    };
  },
  created() {
    this.getData();
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      var isShangwu = row.isShangwu;
      if (isShangwu === '1') {
        return 'warning-isShangwu';
      }
      return '';
    },
    closeXiaDia(val) {
      this.getData();
    },
    handleChangeAudiDate() {
      // 假设我们要转换到东八区（北京时间）
      const timezoneOffset = new Date().getTimezoneOffset();
      const offset = 8 * 60 - timezoneOffset; // 东八区比UTC偏前8小时
      const date = new Date(
        this.searchBody.audiDate.getTime() + offset * 60000
      );
      this.searchBody.audiDate = date;
      // 现在 date 是东八区的时间
      console.log("东八区时间:", date);
    },
    onSearchTypeChange(key) {
      let val;
      for (let key2 of ["yezhu", "phone", "orderNo", "id"]) {
        val = this.searchBody[key2] || val;
      }
      this.searchBody = Object.assign(this.searchBody, {
        [key]: val,
      });
    },
    getData() {
      this.loading.list = true;
      const { timeRange, userIdList, ...rest } = this.searchBody;
      const [startTime, endTime] = timeRange || [null, null];
      /*const _userIdList = (userIdList || []).reduce((a, b) => {
        return Array.from(new Set(a.concat(b)));
      }, []);*/
      var regionId = null;
      if (this.regionIdList != null) {
        var length = this.regionIdList.length;
        regionId = this.regionIdList[length - 1];
      }
      selecJiaOrderPageDataForShangwu({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        startTime: startTime,
        endTime: endTime,
        regionId:regionId,
        ...rest,
      }).then(({ result }) => {
        this.list = result?.data || [];
        this.totalCount = result?.totalCount || "-";
        this.loading.list = false;
      });
      selectRegionTree().then(({ result }) => {
        this.regionTree = result || [];
      });
      /*selectTotalOrderPrice({
        startTime: startTime,
        endTime: endTime,

        ...rest,
      }).then(({ result }) => {
        this.totalOrderPrice = result.orderPrice;
      });*/
    },
    getData2() {},
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    handleSelectionChange(val) {
      this.selectIds = val.map((d) => d.id);
    },
    onSearch() {
      this.pageNo = 1;
      this.getData();
    },
    onReset() {
      this.pageNo = 1;
      this.searchBody = getDefaultSearchBody();
      this.getData();
    },

    handleClick(type, row, title) {
      this.handleType = type;
      switch (type) {
        case "shanchu":

          this.$confirm(`确认删除？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            shangwuShanchuOrder({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;
        case "createNewOrder":
          this.diaShow = true;
          this.$refs.xiaDiaShangwuRef.openDia(this.xiangData,"createNew");

          break;
        case "xiangqing":
          selectJiaOrderDetailVoForShangwu({
            id: row.id,
          }).then((res) => {
            this.xiangData = res.result;
            this.$refs.xiaDiaShangwuRef.openDia(this.xiangData,"xiangqing");
          });
          break;
        case "liangfang":
          this.$confirm(`确认已量房？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            houtaiSetLiangfang({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;

        case "exportOut":
          const { timeRange, userIdList, ...rest } = this.searchBody;
          const [startTime, endTime] = timeRange || [null, null];
          exportJiazhuangOrderList({
            startTime: startTime,
            endTime: endTime,
            phone: this.searchBody.phone,
            audiDateStr: this.searchBody.audiDate,
            zhuangtai: this.searchBody.zhuangtai,
          }).then((res) => {
            let fileName = res.headers["content-disposition"].replaceAll(
              /.*?filename=(.*?)/g,
              "$1"
            );
            downloadFile(res.data, decodeURI(fileName), "blob");
            this.$message.success("导出成功");
          });
          break;
        case "paidan":
          this.dialogTitle3 = "订单ID:" + row.id + "-派单";
          selectPaidanPageVo({
            id: row.id,
          }).then((res) => {
            const paidanData = res.result || {};
            paidanData.orderId = row.id;
            this.paidanData = paidanData;
            this.paidanDialog = true;
          });
          break;
        case "shenhe":
          this.shenheLoading = true;

          this.$confirm(`确认审核通过？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            jiazhuangdingdanshenhe({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
              this.shenheLoading = false;
            });
          });
          break;
        default:
          return;
      }
    },

    queren() {
      this.editDialog = false;
    },

    handleSure(type) {
      type = type || this.handleType;
      const { addrCode, ...rest } = this.updateForm;
      const [provinceCode, cityCode, areaCode] = addrCode;
      switch (type) {
        case "paidan":
          paidanOrder({
            orderId: this.paidanData.orderId,
            jiazhuangPlatformIdList: this.selectRow.map((d) => {
              return d.jiazhuangPlatformId;
            }),
          }).then((res) => {
            this.$message.success("派单成功");
            this.paidanDialog = false;
          });
          break;
        default:
          return;
      }
    },
    onSelectionChange(val) {
      this.selectRow = val;
    },
    handleCommand(command) {
      this.$message("click on item " + command);
    },
    uploadData(params) {
      const form = new FormData();
      form.append("file", params.file);
      const loading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      exportInData(form)
        .then((res) => {
          this.$message.success("导入成功");
          loading.close();
        })
        .catch(() => {
          loading.close();
        });
    },
    beforeUpload(file) {
      if (file.size > 1 * 1024 * 1024) {
        this.$message.warning("上传的文件大小不能超过1MB!");
        return false;
      }
    },
  },
};
</script>

<style>
.power_right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 30px;
  margin-bottom: 10px;
}

.dialookbox {
  border: 1px solid red;
  min-height: 400px;
}

 .el-table .warning-isShangwu {
   background: rgba(126, 232, 197, 0.8);
 }

.el-table .success-row {
  background: #f0f9eb;
}

</style>
